#include "RingQueue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include <iostream>

void* Productor(void* args)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(args);

    while(true)
    {
        int left = rand() % 100;
        usleep(rand() % 100);
        int right = rand() % 100;
        usleep(rand() % 100);
        char oper = Task::opers[rand() % Task::opers.size()];

        Task task(left, right, oper);
        rq->Push(task);
        std::cout << task.PrintTask() << std::endl;
    }
}

void* Consumer(void* args)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(args);

    while(true)
    {
        sleep(1);
        Task task;
        rq->Pop(&task);
        task();

        std::cout << task.PrintResult() << std::endl;
    }

}
int main()
{
    srand(time(nullptr));
    RingQueue<Task>* rq = new RingQueue<Task>();

    pthread_t p[3], c[2];
    pthread_create(&p[0], nullptr, Productor, rq);
    pthread_create(&p[1], nullptr, Productor, rq);
    pthread_create(&p[2], nullptr, Productor, rq);

    pthread_create(&c[1], nullptr, Consumer, rq);
    pthread_create(&c[2], nullptr, Consumer, rq);

    pthread_join(p[0], nullptr);   //没有join就不跑了，因为主线程没了
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
}